import os
import gitlab
from log import logger


def clone_project(url, group_path):
    group_path = group_path.replace("/", "\\")
    isExists = os.path.exists(group_path)
    if not isExists:
        os.makedirs(group_path)
    os.chdir(group_path)
    logger.info('==== clone project: %s %s', url, group_path)
    # TODO 暂时注释掉clone过程，待测试
    # subprocess.call(['git', 'clone', url])
    return


def clone_all(url, private_token, base_path):
    success = True
    # TODO  定义gitlab对象
    gl = gitlab.Gitlab(url, private_token)

    # TODO  遍历group，创建目录
    groups = gl.groups.list(get_all=True)
    for group in groups:
        logger.info('==== group: %s =================================================================', group.full_name)
        logger.debug("group详细信息: %s", group)

        # TODO  遍历project，clone到本地
        projects = group.projects.list()
        for project in projects:
            logger.debug('%s %s %s %s ', project.id, project.name, project.description, project.http_url_to_repo)
            group_path = base_path + "\\" + group.full_path
            clone_project(project.http_url_to_repo, group_path)

    return success


def clone_group(url, private_token, base_path, group_name):
    success = True
    # TODO  定义gitlab对象
    gl = gitlab.Gitlab(url, private_token)

    # TODO  遍历group，创建目录
    groups = gl.groups.list(get_all=True)
    for group in groups:
        # 获取group name 前缀
        group_name_prefix = group.full_name.split(" ", -1)[0]
        # 只匹配第一层group
        if (group.name != group_name) & (group_name_prefix != group_name):
            logger.info("==== group name 不匹配，跳过：%s", group.full_name)
            continue

        logger.info("==== group name 匹配，下载代码")
        logger.info('==== group: %s =================================================================', group.full_name)
        logger.debug("group详细信息: %s", group)

        # TODO  遍历project，clone到本地
        projects = group.projects.list()
        logger.info('==== cloning %s projects',len(projects))
        for project in projects:
            logger.debug('%s %s %s %s ', project.id, project.name, project.description, project.http_url_to_repo)
            group_path = base_path + "\\" + group.full_path
            clone_project(project.http_url_to_repo, group_path)

    return success


url = 'https://oem-git.dasouche-inc.net/';
private_token = 'qmWYcsG9U3RxyLDfejaq';
base_path = r'D:\learn\tmp'

clone_group(url, private_token, base_path, "x-ucar")
